<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>批次查询</span>
        </div>
      </template>
      
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
        <el-form-item label="批次号" prop="batchCode">
          <el-input
            v-model="queryParams.batchCode"
            placeholder="请输入批次号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="请选择产品分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="批次状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择批次状态" clearable>
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="质量状态" prop="qualityStatus">
          <el-select v-model="queryParams.qualityStatus" placeholder="请选择质量状态" clearable>
            <el-option
              v-for="dict in qualityStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="plannedDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="实际日期">
          <el-date-picker
            v-model="actualDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Search"
            @click="handleBatchTrace"
            :disabled="!selectedBatchCode"
          >批次追溯</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['qep:production:batch:export']"
          >导出报表</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange" @row-click="handleRowClick">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="批次号" align="center" prop="batchCode" />
        <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
        <el-table-column label="产品分类" align="center" prop="categoryName" :show-overflow-tooltip="true" />
        <el-table-column label="计划数量" align="center" prop="plannedQuantity" />
        <el-table-column label="实际数量" align="center" prop="actualQuantity" />
        <el-table-column label="计划日期" align="center" prop="plannedDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.plannedDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际日期" align="center" prop="actualDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getBatchStatusType(scope.row.status)">
              {{ getBatchStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="质量状态" align="center" prop="qualityStatus">
          <template #default="scope">
            <el-tag :type="getQualityStatusType(scope.row.qualityStatus)">
              {{ getQualityStatusText(scope.row.qualityStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button 
              link type="primary" 
              icon="View" 
              @click="handleView(scope.row)"
              v-hasPermi="['qep:production:batch:query']"
            >查看</el-button>
            <el-button 
              link type="primary" 
              icon="Search" 
              @click="handleProcessFlow(scope.row)" 
              v-hasPermi="['qep:production:process:flow']"
            >工序</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 批次追溯对话框 -->
    <el-dialog title="批次追溯" v-model="traceOpen" width="900px" append-to-body>
      <el-descriptions title="批次基本信息" :column="2" border>
        <el-descriptions-item label="批次号">{{ traceInfo.batchCode }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ traceInfo.productName }}</el-descriptions-item>
        <el-descriptions-item label="计划数量">{{ traceInfo.plannedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="实际数量">{{ traceInfo.actualQuantity || '-' }}</el-descriptions-item>
      </el-descriptions>

      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in traceInfo.activities"
          :key="index"
          :timestamp="activity.timestamp"
          :type="activity.type"
          :color="activity.color"
          :size="activity.size"
          :hollow="activity.hollow"
        >
          <el-card>
            <template #header>
              <h4>{{ activity.title }}</h4>
            </template>
            <p v-html="activity.content"></p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import { listBatches, exportBatchReport, traceBatch } from '@/api/qep/production'
import { listCategory } from '@/api/qep/category'

const router = useRouter()

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = computed(() => ids.value.length !== 1)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 批次表格数据
const batchList = ref([])
// 选中的批次号
const selectedBatchCode = ref('')
// 是否显示批次追溯弹窗
const traceOpen = ref(false)
// 批次追溯信息
const traceInfo = reactive({
  batchCode: '',
  productName: '',
  plannedQuantity: 0,
  actualQuantity: 0,
  activities: []
})
// 产品分类选项
const categoryOptions = ref([])
// 计划日期范围
const plannedDateRange = ref([])
// 实际日期范围
const actualDateRange = ref([])

// 批次状态选项
const statusOptions = [
  { value: 'PLANNED', label: '计划中' },
  { value: 'IN_PROGRESS', label: '生产中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CANCELLED', label: '已取消' }
]

// 质量状态选项
const qualityStatusOptions = [
  { value: 'PENDING', label: '待检测' },
  { value: 'INSPECTING', label: '检测中' },
  { value: 'PASSED', label: '合格' },
  { value: 'FAILED', label: '不合格' },
  { value: 'REWORK', label: '返工' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  batchCode: undefined,
  productName: undefined,
  categoryId: undefined,
  status: undefined,
  qualityStatus: undefined
})

// 获取批次状态类型
const getBatchStatusType = (status) => {
  if (status === 'PLANNED') return 'info'
  if (status === 'IN_PROGRESS') return 'warning'
  if (status === 'COMPLETED') return 'success'
  if (status === 'CANCELLED') return 'danger'
  return 'info'
}

// 获取批次状态文本
const getBatchStatusText = (status) => {
  const statusMap = {
    'PLANNED': '计划中',
    'IN_PROGRESS': '生产中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 获取质量状态类型
const getQualityStatusType = (status) => {
  if (status === 'PENDING') return 'info'
  if (status === 'INSPECTING') return 'warning'
  if (status === 'PASSED') return 'success'
  if (status === 'FAILED') return 'danger'
  if (status === 'REWORK') return 'warning'
  return 'info'
}

// 获取质量状态文本
const getQualityStatusText = (status) => {
  const statusMap = {
    'PENDING': '待检测',
    'INSPECTING': '检测中',
    'PASSED': '合格',
    'FAILED': '不合格',
    'REWORK': '返工'
  }
  return statusMap[status] || status
}

/** 查询批次列表 */
function getList() {
  loading.value = true
  // 处理日期范围参数
  const params = {
    ...queryParams,
    plannedStartDate: plannedDateRange.value && plannedDateRange.value.length > 0 ? plannedDateRange.value[0] : undefined,
    plannedEndDate: plannedDateRange.value && plannedDateRange.value.length > 0 ? plannedDateRange.value[1] : undefined,
    actualStartDate: actualDateRange.value && actualDateRange.value.length > 0 ? actualDateRange.value[0] : undefined,
    actualEndDate: actualDateRange.value && actualDateRange.value.length > 0 ? actualDateRange.value[1] : undefined
  }
  
  listBatches(params).then(response => {
    batchList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询产品分类列表 */
function getCategoryOptions() {
  listCategory().then(response => {
    categoryOptions.value = response.rows
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  plannedDateRange.value = []
  actualDateRange.value = []
  queryParams.batchCode = undefined
  queryParams.productName = undefined
  queryParams.categoryId = undefined
  queryParams.status = undefined
  queryParams.qualityStatus = undefined
  queryParams.pageNum = 1
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  if (selection.length > 0) {
    selectedBatchCode.value = selection[0].batchCode
  } else {
    selectedBatchCode.value = ''
  }
}

/** 行点击事件 */
function handleRowClick(row) {
  selectedBatchCode.value = row.batchCode
}

/** 查看详情按钮操作 */
function handleView(row) {
  router.push({ path: '/production/batch/detail', query: { id: row.id } })
}

/** 跳转到工序流转页 */
function handleProcessFlow(row) {
  router.push({ path: '/production/process/flow', query: { batchId: row.id } })
}

/** 导出按钮操作 */
function handleExport() {
  // 处理日期范围参数
  const params = {
    ...queryParams,
    plannedStartDate: plannedDateRange.value && plannedDateRange.value.length > 0 ? plannedDateRange.value[0] : undefined,
    plannedEndDate: plannedDateRange.value && plannedDateRange.value.length > 0 ? plannedDateRange.value[1] : undefined,
    actualStartDate: actualDateRange.value && actualDateRange.value.length > 0 ? actualDateRange.value[0] : undefined,
    actualEndDate: actualDateRange.value && actualDateRange.value.length > 0 ? actualDateRange.value[1] : undefined
  }
  
  exportBatchReport(params).then(response => {
    // 处理导出逻辑
  })
}

/** 批次追溯按钮操作 */
function handleBatchTrace() {
  if (!selectedBatchCode.value) {
    ElMessage.warning("请先选择要追溯的批次")
    return
  }
  
  loading.value = true
  traceBatch(selectedBatchCode.value).then(response => {
    const data = response.data
    
    // 基础信息
    traceInfo.batchCode = data.batchCode
    traceInfo.productName = data.productName
    traceInfo.plannedQuantity = data.plannedQuantity
    traceInfo.actualQuantity = data.actualQuantity
    
    // 活动记录
    traceInfo.activities = data.activities || []
    
    traceOpen.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

onMounted(() => {
  getList()
  getCategoryOptions()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-timeline {
  margin-top: 20px;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style> 